package com.ruoyi.web.exams.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.web.controller.tool.ListUtils;
import com.ruoyi.web.exams.domain.ExamAnswers;
import com.ruoyi.web.exams.domain.ExamOption;
import com.ruoyi.web.exams.domain.ExamQuestion;
import com.ruoyi.web.exams.dto.PostAnswersVo;
import com.ruoyi.web.exams.mapper.ExamAnswersMapper;
import com.ruoyi.web.exams.mapper.ExamOptionMapper;
import com.ruoyi.web.exams.mapper.ExamQuestionMapper;
import com.ruoyi.web.exams.service.IExamAnswersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 答题卡条目Service业务层处理
 *
 * @author 范书铭
 * @date 2024-10-02
 */
@Service
public class ExamAnswersServiceImpl extends ServiceImpl<ExamAnswersMapper, ExamAnswers> implements IExamAnswersService {

    @Resource
    private ExamAnswersMapper examAnswersMapper;
    @Resource
    private ExamQuestionMapper examQuestionMapper;
    @Resource
    private ExamOptionMapper examOptionMapper;


    /**
     * 查询答题卡条目列表
     *
     * @param examAnswers 答题卡条目
     * @return 答题卡条目
     */
    @Override
    public List<ExamAnswers> selectExamAnswersList(ExamAnswers examAnswers) {
        return examAnswersMapper.selectExamAnswersList(examAnswers);
    }

    @Override
    public boolean postAnswer(PostAnswersVo postAnswersVo) {
        // 将答案填充
        ExamAnswers examAnswers = new ExamAnswers();
        BeanUtils.copyProperties(postAnswersVo, examAnswers);
        //判断用户答案是否正确
//        ExamQuestion examQuestion = examQuestionMapper.selectById(examAnswers.getQuestionId());
        List<ExamOption> options = examOptionMapper.selectList(new LambdaQueryWrapper<ExamOption>()
                .eq(ExamOption::getQuestionId, examAnswers.getQuestionId()));

        List<String> optionTags = options.stream()
                .filter(ExamOption::getIsRight)
                .map(ExamOption::getOptionTag)
                .collect(Collectors.toList());
        examAnswers.setUserAnswerStatus(ListUtils.isAnswerOptionsRight(optionTags, postAnswersVo.getUserAnswerOptionIds()) ? 2 : 1);
        return examAnswersMapper.updateById(examAnswers) > 0;
    }

}